/**
 *  通用方法
 */
layui.extend({
    setter: 'config'
    , view: 'lib/view'
    , verifyLimit: 'lib/verifyLimit'
}).define(['setter', 'layer', 'laytpl','table', 'element', 'util', 'view', 'laypage','verifyLimit'], function (exports) {
    var setter = layui.setter, layer = layui.layer, $ = layui.jquery, view = layui.view,verifyLimit = layui.verifyLimit,
        laytpl = layui.laytpl, laypage = layui.laypage,table=layui.table,$body = $('body'),
        fn = {
            $loading: null,
            $copyContent: null,
            reg: {
                phone: /^1\d{10}$/
                ,mail: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
                ,name: /^[\u2E80-\u9FFF]+$/
            }
            , trim: function (va) {
                va = va || '';
                return va.toString().replace(/(^\s*)|(\s*$)/g, "");
            }
            , isEmpty: function (va) {
                if (!va) {
                    return true;
                }
                if (fn.trim(va).length == 0) {
                    return true;
                }
                return false
            }
            , isNotEmpty: function (val) {
                return !fn.isEmpty(val);
            }
            , removeNull: function (va) {
                return (this.isEmpty(va) || va == 'null') ? '' : va;
            }
            , showLoading: function () {
                fn.$loading.fadeIn();
            }
            , hideLoading: function () {
                fn.$loading.fadeOut(200);
            }
            , zmLoad: function (e) {
                var $this = e || $('[zm-load]');
                $this.each(function (i, o) {
                    $.get($(o).attr('zm-load'), {'v': setter.version}, function (res) {
                        var data = setter.data;
                        data['user'] = fn.getUser()['loginInfo'];
                        laytpl(res).render(data, function (html) {
                            $(o).html(html);
                        })
                    });
                });
            }
            , getUrlParam: function (name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                if (location.href.indexOf('?') != -1) {
                    var r = location.href.substr(location.href.indexOf('?') + 1).match(reg);
                    if (r != null) return unescape(r[2]);
                }
                return null;
            }
            , stateInterception: function(res) {
                switch (res.code) {
                    case '1':
                        return true;
                    case '0':
                        layer.msg(res.message||'系统繁忙,请稍后重试');
                        return false;
                    case '429':
                        fn.setLocalStorage('limitRequestId', res.limitRequestId);
                        verifyLimit.show();
                        return false;
                    case '401':
                        fn.setLocalStorageJson('$user', {});
                        location.href = '/login.html?original=' + encodeURIComponent(parent.location.href);
                        return false;
                    default:
                        return false;
                }
            }
            , isSuccess: function (res) {
                fn.hideLoading();
                var st = fn.stateInterception(res);
                if (!st) {
                    layer.msg(res.message);
                }
                return st;
            }
            ,isSuccessWarn: function (res) {
                fn.hideLoading();
                var st = fn.stateInterception(res);
                if (!st) {
                    layer.alert(res.message,{icon:3});
                }
                return st;
            }
            , setLocalStorage: function (key, val) {
                localStorage.setItem(key, val);
            }
            , setLocalStorageJson: function (key, val) {
                localStorage.setItem(key, JSON.stringify(val));
            }
            , getLocalStorage: function (key) {
                return localStorage.getItem(key);
            }
            , getLocalStorageJson: function (key) {
                let val = fn.getLocalStorage(key);
                return fn.isNotEmpty(val) ? JSON.parse(val) : null;
            }
            , getUser: function () {
                return fn.getLocalStorageJson('$user') || {};
            }
            , getPerson: function(){
                let user = fn.getUser();
                return (user && user.loginInfo)?user.loginInfo:{};
            }
            ,refPerson: function(person){
                let user = fn.getUser();
                user.loginInfo = person;
                fn.setLocalStorageJson('$user', user);
            }
            ,logout: function(){
                fn.showLoading();
                $.post('/scm/auth/logout',function () {
                    fn.setLocalStorageJson('$user', {});
                    location.href = '/index.html';
                });
            }
            , alertWarn: function(c, fn) {
                return layer.alert(c, {icon: 0, title: '系统提示',closeBtn:false}, fn);
            }
            ,alertSuccess: function (c, fn) {
                return layer.alert(c, {icon: 1, title: '系统提示',closeBtn:false}, fn);
            }
            ,confirm_inquiry:function (t,fn) {
                layer.confirm(t,{icon: 3,closeBtn:false,title:'温馨提示'},function(index){
                    layer.close(index);
                    if(fn){var _FN = eval(fn);_FN();}
                });
            }
            ,tipsMessage:function (innerText,ele,flag) {
                if(flag){
                    setTimeout(function(){
                        layer.tips(innerText,ele,{tips: [2,'#ff0000'], //在元素的下面出现 1上面，2右边 3下面
                            tipsMore: true, //允许同时存在多个
                            time:2000 //tips自动关闭时间，毫秒
                        });
                    },500);
                }else{
                    layer.tips(innerText,ele,{//所需提醒的元素
                        tips: [2,'#ff0000'], //在元素的下面出现 1上面，2右边 3下面
                        tipsMore: true, //允许同时存在多个
                        time:2000 //tips自动关闭时间，毫秒
                    });
                }
            }
            , formatCurrency: function (num) {
                if (num == '' || num == null || num == 'null' || num == 0) {
                    return '0.00';
                }
                num = num.toString().replace(/\$|\,/g, '');
                if (isNaN(num)) {
                    num = "0"
                }
                ;sign = (num == (num = Math.abs(num)));
                num = Math.floor(num * 100 + 0.50000000001);
                cents = num % 100;
                num = Math.floor(num / 100).toString();
                if (cents < 10) {
                    cents = "0" + cents
                }
                ;
                for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
                    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
                }
                return (((sign) ? '' : '-') + num + '.' + cents);
            }
            ,contain: function(array,val) {for (var i = 0; i < array.length; i++) {if (array[i] == val) {return true;}}return false;}
            ,uuid: function(){var d = new Date().getTime();if (window.performance && typeof window.performance.now === "function") {d += performance.now();}var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {var r = (d + Math.random() * 16) % 16 | 0;d = Math.floor(d / 16);return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);});return uuid;}
            , startCopyContent: function(e) {
                fn.$copyContent.val(e.parent().text().trim()).select();
                document.execCommand("copy");
                layer.tips('已复制', e.parent(), {tips: [1, '#333'], time: 2000});
            }
            ,getNowFormatDate(){var date = new Date();var seperator1 = "-";var year = date.getFullYear();var month = date.getMonth() + 1;var strDate = date.getDate();if (month >= 1 && month <= 9) {month = "0" + month;}if (strDate >= 0 && strDate <= 9) {strDate = "0" + strDate;}var currentdate = year + seperator1 + month + seperator1 + strDate;return currentdate;}
            ,fullSelect: function(opts){
                let options = $.extend({elem:null,data:[],label:'label',value:'value',defValue:'',firstLabel:''},(opts || {}));
                options.elem.get(0).length = 0;
                if(fn.isNotEmpty(options.firstLabel)){
                    options.elem.append('<option value="">'+options.firstLabel+'</option>')
                }
                $.each(options.data || [],function (i,item) {
                    options.elem.append('<option value="'+item[options.value]+'"'+(fn.isNotEmpty(options.defValue) && item[options.value] == options.defValue?' selected':'')+'>'+item[options.label]+'</option>');
                });
            }
            , createCopyContent: function() {
                $(".copy").each(function () {
                    var othis = $(this);
                    othis.parent().append('<a href="javascript:" class="copy-btn" title="复制" zmark-event="layui.com.startCopyContent"><i class="iconfont iconfuzhi f14"></i></a>');
                    othis.removeClass('copy');
                });
            }
            // 验证表单
            ,validateForm: function($form){
                let forms = $form.find('.required').filter(':visible').not('.disabled').not(':input[disabled]');
                for(var i=0;i<forms.size();i++){
                    let $item = $(forms[i]);
                    if(fn.isEmpty($item.val())){
                        $item.addClass('layui-form-danger').focus();
                        layer.msg('必填项不能为空');
                        return false;
                    }
                }
                return true;
            }
            ,jsonList: function(json){var list = [],keys=[];for(var key in json){keys.push(key);}$.each(json[keys[0]] ||[],function (i,o) {var item = {};$.each(keys,function (j,k) {item[k] = json[k][i];});list.push(item);});return list;}
            , pagination: function(elem, count, params, callback) {
                laypage.render({
                    elem: elem
                    , count: count
                    , limit: params.limit
                    , curr: params.page
                    , layout: ['count','limit', 'prev', 'page', 'next']
                    , jump: function (obj, first) {
                        if (!first) {
                            params.page = obj.curr;
                            params.limit = obj.limit;
                            if (callback) {
                                callback.call();
                            }
                        }
                    }
                });
            }
            , paginationNoLimit: function(elem, count, params, callback) {
                laypage.render({
                    elem: elem
                    , count: count
                    , limit: params.limit
                    , curr: params.page
                    , layout: ['count', 'prev', 'page', 'next']
                    , jump: function (obj, first) {
                        if (!first) {
                            params.page = obj.curr;
                            params.limit = obj.limit;
                            if (callback) {
                                callback.call();
                            }
                        }
                    }
                });
            }
            , checkDecimal: function($that, digit) {
                $that.val($that.val().trim().replace(',', ''));
                let expression = {
                    2:/^[\+\-]?\d*?\.?\d{0,2}?$/
                    ,4:/^[\+\-]?\d*?\.?\d{0,4}?$/
                };
                if (!$that.val().match(expression[digit])) {
                    $that.val($that.attr('t_value'));
                } else {
                    $that.attr({'t_value': $that.val()});
                }
                if ($that.val().match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/)) {
                    $that.attr({'o_value': $that.val()});
                }
            }
            ,checkInt: function($that){
                $that.val($that.val().replace(/\D/g, ""));
            }
            ,chooseCheckbox: function(elem,checked){
                $.each(elem,function (i,item) {
                    item.checked = checked;
                });
                // elem.each((i,item) => {
                //     item.checked = checked;
                // });
            }
            , init: function () {
                fn.zmLoad();
                fn.createCopyContent();
                $(".picker-month").attr({"autocomplete":"off","readonly":true}).focus(function(){WdatePicker({dateFmt:"yyyy-MM"})}).click(function(){WdatePicker({dateFmt:"yyyy-MM"})});
                $('.picker-date').attr({"autocomplete":"off","readonly":true}).focus(function(){WdatePicker()}).click(function(){WdatePicker()});
                $('.picker-time').attr({"autocomplete":"off","readonly":true}).focus(function(){WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'})}).click(function(){WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'})});
            }
            ,getNowFormatDate: function(){
                var date = new Date();
                var seperator1 = "-";
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                var currentdate = year + seperator1 + month + seperator1 + strDate;
                return currentdate;
            }
            ,formatDate: function(date,fmt){
                var o = {
                    "M+": date.getMonth() + 1, //月份 
                    "d+": date.getDate(), //日 
                    "h+": date.getHours(), //小时 
                    "m+": date.getMinutes(), //分 
                    "s+": date.getSeconds(), //秒 
                    "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
                    "S": date.getMilliseconds() //毫秒 
                   };
                   if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                   for (var k in o)
                   if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                   return fmt;
            }
            ,conversionDays: function(data){
                let odata = new Date(),fdata=data.split(' ')[0];
                if(fn.formatDate(odata,'yyyy-MM-dd')==fdata){
                    return '今天';
                }
                odata.setDate(odata.getDate()-1);
                if(fn.formatDate(odata,'yyyy-MM-dd')==fdata){
                    return '昨天';
                }
                return fdata;
            }
            ,conversionTime: function(data){

            }
            ,phoneSecret: function(phoneNo){
                if(fn.isNotEmpty(phoneNo) && phoneNo.length == 11) {
                    phoneNo = phoneNo.substr(0,3) + "****" + phoneNo.substr(7);
                }
                return phoneNo;
            }
            ,abbreviation: function(val,len) {
               if(fn.isNotEmpty(val) && val.length > len) {
                   val = val.substr(0,len) + '...';
               }
               return val;
            },
            tabRadioChoice:function (obj,tabId) {
                let inx = obj.tr.attr('data-index');
                $.each(table.cache[tabId],function (i,o) {
                    let index= o['LAY_TABLE_INDEX'],$tr = $('.layui-table-view[lay-id="'+tabId+'"] tr[data-index=' + index + ']'),$itemRadio = $tr.find('input[type="radio"]');
                    if(inx==index){
                        o["LAY_CHECKED"] = true;
                        $itemRadio.prop('checked', true);
                        $itemRadio.next().addClass('layui-form-radioed');
                        $itemRadio.next().find('.layui-anim ').remove();
                        $itemRadio.next().append('<i class="layui-anim layui-icon layui-anim-scaleSpring"></i>');
                        $tr.addClass('layui-table-click');
                    }else{
                        o["LAY_CHECKED"] = false;
                        $itemRadio.prop('checked', false);
                        $itemRadio.next().removeClass('layui-form-radioed');
                        $itemRadio.next().find('.layui-anim ').remove();
                        $itemRadio.next().append('<i class="layui-anim layui-icon"></i>');
                        $tr.removeClass('layui-table-click');
                    }
                });
            },
            tabCheckboxChoice:function (obj,tabId) {
                let inx = obj.tr.attr('data-index'),rchecked=false;
                $.each(table.cache[tabId], function (i, o) {
                    let index = o['LAY_TABLE_INDEX'],
                        $tr = $('.layui-table-view[lay-id="' + tabId + '"] tr[data-index=' + index + ']'),$itemCheckbox = $tr.find('input[type="checkbox"]');
                    if(inx==index){
                        if(o["LAY_CHECKED"]){
                            o["LAY_CHECKED"] = false;
                            $itemCheckbox.prop('checked', false);
                            $itemCheckbox.next().removeClass('layui-form-checked');
                            $tr.removeClass('layui-table-click');
                        }else{
                            o["LAY_CHECKED"] = true;
                            $itemCheckbox.prop('checked', true);
                            $itemCheckbox.next().addClass('layui-form-checked');
                            $tr.addClass('layui-table-click');
                            rchecked = true;
                        }
                    }
                });
                return rchecked;
            },
            addTask:function(taskId){
                let optask = fn.getLocalStorage('optask') || '[]';
                let optaskArray = JSON.parse(optask);
                optaskArray.push(taskId);
                fn.setLocalStorage('optask',JSON.stringify(optaskArray));
            },
            clearTask:function(taskId){
                let optask = fn.getLocalStorage('optask') || '[]';
                let optaskArray = JSON.parse(optask).filter(({ item }) => item !== taskId);
                fn.setLocalStorage('optask',JSON.stringify(optaskArray));
            }
        };
    fn.init();
    $.fn.serializeJson = function () {
        var serializeObj = {}, $this = $(this), array = this.serializeArray();
        $(array).each(function () {
            if (typeof(serializeObj[this.name]) != "undefined") {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                var isList = (typeof($this.find('[name="' + [this.name] + '"]').attr("LIST")) == "undefined");
                serializeObj[this.name] = (isList) ? this.value : [this.value];
            }
        });
        return serializeObj;
    };
    $.fn.extend({enter:function (fn,thisObj) {var obj = thisObj || this;return this.each(function () {$(this).keyup(function(event){if(event.keyCode == 13){fn.call(obj,event);}});});}});
    // 加载层
    if ($('.lodding').size() == 0) {
        $body.append('<div class="spinner_shade lodding" id="fullLoading"></div><div class="spinner lodding"><div class="lodding_ico"></div><div>正在加载中...</div></div>');
        fn.$loading = $('.lodding');
    }
    //复制文本框
    if ($('#copyContent').size() == 0) {
        $body.append('<input id="copyContent" style="width: 1px;height: 1px;position: fixed;bottom: 0;left: 0;z-index: 0;background-color: transparent;border: 0px"/>');
        fn.$copyContent = $('#copyContent');
    }
    Array.prototype.contain = function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) {
                return true;
            }
        }
        return false;
    };
    $body.on('click', '*[zmark-event]', function () {
        var othis = $(this);
        eval(othis.attr('zmark-event')).call(this, othis);
    });
    $body.on('click', '*[zmark-anim]', function () {
        var othis = $(this);
        othis.addClass(othis.attr('zmark-anim'));
        setTimeout(function () {
            othis.removeClass(othis.attr('zmark-anim'));
        }, 1000);
    });
    $body.on('click', '*[refresh-template]', function () {
        view($(this).attr('refresh-template')).refresh();
    });
    $body.on('click', '*[zmark-more-operation] a', function () {
        let othis = $(this),pthis=othis.parent().parent().parent().parent();
        pthis.find('a').removeClass('curr');
        othis.addClass('curr');
        pthis.find('.more-operation-txt div').html(othis.text());
        eval(pthis.attr('zmark-more-operation')).call(this, othis);
        pthis.addClass('active');
        setTimeout(function () {
            pthis.removeClass('active');
        },100);
    });
    $body.on('keyup', 'input[NUMBER]', function () {
        var othis = $(this);
        fn.checkDecimal(othis, parseInt(othis.attr('NUMBER') || '2'));
    });
    $body.on('blur', 'input[NUMBER]', function () {
        var othis = $(this);
        fn.checkDecimal(othis, parseInt(othis.attr('NUMBER') || '2'));
    });
    $body.on('keyup', 'input[INT]', function () {
        fn.checkInt($(this));
    });
    $body.on('blur', 'input[INT]', function () {
        fn.checkInt($(this));
    });
    $body.on('focus', 'input[CLEARZERO]', function () {
        var othis = $(this);
        if(fn.isNotEmpty(othis.val()) && parseFloat(othis.val()) == 0){
            othis.val('');
        }
    });
    $body.on('blur', 'input[CLEARZERO]', function () {
        var othis = $(this);
        if(fn.isEmpty(othis.val())){
            othis.val('0');
        }
    });
    $body.on('click', 'a[close-tooltip]', function () {
        $(this).parent().parent().remove();
    });
    if (window.ActiveXObject || "ActiveXObject" in window){
        $body.append('<link rel="stylesheet" href="/style/ie.css?v='+setter.version+'" media="all">');
    }
    //监听浏览器关闭事件
    window.onbeforeunload = function closeWindow(e){
        //清除定时器，防止无谓的请求到后台
        clearInterval();
        return;
    };
    exports('com', fn);
});